#!/usr/bin/python
# -*- coding: utf-8 -*-

import os
import datetime
import re


from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.api import memcache
from django.utils import translation
from django.conf import settings as django_settings

import gmemsess 
#import settings

template.register_template_library('common.my_filter_tag')


def settings(request):
  d = dict([(k, getattr(django_settings, k)) 
            for k in django_settings.get_all_members()])
  return dict(**d)

def TextToHtml(text):
    text = text.replace("\r\n", "<br>")
    text = text.replace("\r", "<br>")
    text = text.replace("\n", "<br>")
    text = text.replace("\t", "&emsp;")
    return text

def GetUserLoginID():
    User = users.get_current_user()
    if None == User:
        return ''
    else:
        return User.user_id()

def GetUserNickname():
    User = users.get_current_user()
    if None == User:
        return ''
    else:
        return User.nickname()

def UserIsAdmin():
    return users.is_current_user_admin()


def ResetLanguage(request):
    language = translation.get_language_from_request(request)
    translation.activate(language)
    return translation.get_language()

def GetCurLanguage():
    return translation.get_language()

def GetDefaultTemplateValue(request):
    UserID = GetUserLoginID()
    try:
        Uri = request.uri
    except:
        Uri = ""
        
    LogUrl = users.create_login_url(Uri)
    if UserID:
        LogUrl = users.create_logout_url(Uri)

    TemplateValues = {'LogUrl':LogUrl, 'UserID':UserID, 'UserName':GetUserNickname(), 'IsAdmin':UserIsAdmin(),
                      'IsFeed':False,'IsAjax':False, }
    return TemplateValues


#def GetOneUserLoginName(NickName):
#    if NickName:
#        RetName = NickName
#        OneUserInfo = databasefunction.GetOneUserInfoFromNickName(NickName)
#        if OneUserInfo:
#            RetName = OneUserInfo.LoginName
#
#        return RetName
#    else:
#        return ''

def GetDatetimeFromString(DateTimeString):
    if 1 > len(DateTimeString):
        return None

    Rule = re.compile(r"\d+")
    Find = Rule.findall(DateTimeString)
    return datetime.datetime( int(Find[0]), int(Find[1]), int(Find[2]), int(Find[3]), int(Find[4]), int(Find[5]), int(Find[6]) )


def GetUTCDateTimeFromLocalString(LocalDateTimeString, TimeDelta):
    UTCDateTime = GetDatetimeFromString(LocalDateTimeString)
    return UTCDateTime - TimeDelta


def GetEmptyNickName(TimeDelta):
    return translation.gettext("anonymous")



class CBasePage(webapp.RequestHandler):
#    def GetUserNameAndWhetherAdmin(self):
#        LoginID = GetUserLoginID()
#        if 0 < len(LoginID):
#            RetName = LoginName
#            OneUserInfo = databasefunction.GetOneUserInfo(LoginName)
#            if OneUserInfo:
#                if OneUserInfo.NickName:
#                    RetName = OneUserInfo.NickName
#            else:
#                databasefunction.AddCurrentUserToUserTable(self.GetTheSessionLanguage())
#
#            return RetName, UserIsAdmin()
#        else:
#            return None, False


    def GetBaseDefaultTemplateValue(self):
        return GetDefaultTemplateValue(self.request)


    def GetClientIP(self):
        return os.environ["REMOTE_ADDR"]

    def ResetLangugeAndTimeDelta(self):
        Sess = gmemsess.Session(self)
        Sess['language'] = translation.get_language()
        try:
            HourOffset = int(translation.gettext("houroffset"))
        except:
            HourOffset = 0
        Sess['timedelta'] = datetime.timedelta(hours=HourOffset)
        
    def GetRightLanguageHtmlFilePath(self, FileName):
#        UserLanguage = translation.get_language()
#        Sess = gmemsess.Session(self)
#        Sess['language'] = UserLanguage
#        try:
#            HourOffset = int(translation.gettext("houroffset"))
#        except:
#            HourOffset = 0
#        Sess['timedelta'] = datetime.timedelta(hours=HourOffset)
        FilePath = os.path.join( os.path.dirname(os.getcwd()),'templates', '%s_cn.html'%(FileName) )
        return FilePath

    def GetTheSessionTimeDelta(self):
        Sess = gmemsess.Session(self)
        if Sess.is_new():
            return datetime.timedelta(0);
        else:
            return Sess['timedelta'];

    def GetTheSessionLanguage(self):
        Sess = gmemsess.Session(self)
        if Sess.is_new():
            return settings.LANGUAGE_CODE;
        else:
            return Sess['language'];
        
